/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Conhecimento_Transporte.java
 *
 * Created on 10/10/2012, 21:05:44
 */

package projeto;

import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import projeto.classes.AnimalAcessaDados;
import projeto.classes.ClienteAcessaDados;
import projeto.classes.ConhecimentoTransporteAcessaDados;
import projeto.classes.ModeloAnimal;
import projeto.classes.ModeloCliente;
import projeto.classes.ModeloConhecimentoTransporte;
import projeto.classes.ModeloMotorista;
import projeto.classes.ModeloVeiculo;
import projeto.classes.MotoristaAcessaDados;
import projeto.classes.Util.Util;
import projeto.classes.VeiculoAcessaDados;

/**
 *
 * @author Angela
 */
public class Conhecimento_Transporte extends javax.swing.JInternalFrame {

    private ModeloConhecimentoTransporte ct;
    private ConhecimentoTransporteAcessaDados ctDao;
    private ArrayList<ModeloConhecimentoTransporte> lista;
    private ArrayList<ModeloAnimal> listaAnimal = new ArrayList<ModeloAnimal>();
    private ArrayList<ModeloCliente> listaCliente = new ArrayList<ModeloCliente>();
    private ArrayList<ModeloMotorista> listaMotorista = new ArrayList<ModeloMotorista>();
    private ArrayList<ModeloVeiculo> listaVeiculo = new ArrayList<ModeloVeiculo>();
    private br.com.fatecpg.mdi.MDI2 mdi;
    
    
    /** Creates new form Conhecimento_Transporte */
    public Conhecimento_Transporte() {
        initComponents();
    }
    
    public Conhecimento_Transporte(projeto.classes.ModeloUsuario user, br.com.fatecpg.mdi.MDI2 mdi) {
        initComponents();
        
        this.mdi = mdi;
        
        //getUsuarioAdmin igual a 0 quer dizer que ele é um usuario normal
        //apenas usuarios adms poderão alterar ou excluir
        if (user.getUsuarioAdmin() == 0) {
            btnExcluir.setVisible(false);
            pnConsulta.setVisible(false);
            btnAlterar.setVisible(false);
        }
        
        if (btnExcluir.isVisible()) {
            btnExcluir.setEnabled(false);
            btnAlterar.setEnabled(false);
        }
        
        mostrarCampos(false);
        
        ct = new ModeloConhecimentoTransporte();
        ctDao = new ConhecimentoTransporteAcessaDados();
        
        //carrega os combos
        carregarComboAnimal();
        carregarComboCliente();
        carregarComboMotorista();
        carregarComboVeiculo();
    }
    
    private void mostrarCampos(boolean flag) {
        cmbAnimal.setEnabled(flag);
        cmbCliente.setEnabled(flag);
        cmbMotorista.setEnabled(flag);
        cmbVeiculo.setEnabled(flag);
        txtData.setEnabled(flag);
        txtOrigem.setEnabled(flag);
        txtDestino.setEnabled(flag);
        txtPeso.setEnabled(flag);
        txtValor.setEnabled(flag);
    }
    
    private void limparCampos() {
        txtData.setText("");
        txtOrigem.setText("");
        txtDestino.setText("");
        txtPeso.setText("");
        txtValor.setText("");
        lblCodigo.setText("--");
        if (cmbAnimal.getItemCount() > 0) {
            cmbAnimal.setSelectedIndex(0);
        }
        if (cmbCliente.getItemCount() > 0) {
            cmbCliente.setSelectedIndex(0);
        }
        if (cmbMotorista.getItemCount() > 0) {
            cmbMotorista.setSelectedIndex(0);
        }
        if (cmbVeiculo.getItemCount() > 0) {
            cmbVeiculo.setSelectedIndex(0);
        }
    }
    
    private void carregarComboAnimal() {
        AnimalAcessaDados dao = new AnimalAcessaDados();
        try {
            listaAnimal = dao.consultaTodos();
             
            
            if (!listaAnimal.isEmpty()) {
                for (int i = 0; i < listaAnimal.size(); i++) {
                    ModeloAnimal a = listaAnimal.get(i);
                    cmbAnimal.addItem(a.getNome());
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void carregarComboCliente() {
        ClienteAcessaDados dao = new ClienteAcessaDados();
        try {
            listaCliente = dao.consultaTodos();
             
            
            if (!listaCliente.isEmpty()) {
                for (int i = 0; i < listaCliente.size(); i++) {
                    ModeloCliente c = listaCliente.get(i);
                    cmbCliente.addItem(c.getNome());
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void carregarComboMotorista() {
        MotoristaAcessaDados dao = new MotoristaAcessaDados();
        try {
            listaMotorista = dao.consultaTodos();
             
            
            if (!listaMotorista.isEmpty()) {
                for (int i = 0; i < listaMotorista.size(); i++) {
                    ModeloMotorista m = listaMotorista.get(i);
                    cmbMotorista.addItem(m.getNome());
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void carregarComboVeiculo() {
        VeiculoAcessaDados dao = new VeiculoAcessaDados();
        try {
            listaVeiculo = dao.consultaTodos();
             
            
            if (!listaVeiculo.isEmpty()) {
                for (int i = 0; i < listaVeiculo.size(); i++) {
                    ModeloVeiculo v = listaVeiculo.get(i);
                    cmbVeiculo.addItem(v.getNomeMarca());
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao carregar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    
    
    private void alterarLabels() {
        lblData.setForeground(Color.black);
        lblDestino.setForeground(Color.black);
        lblValor.setForeground(Color.black);
        lblOrigem.setForeground(Color.black);
        lblPeso.setForeground(Color.black);
        lblCodigo.setForeground(Color.black);
    }
    
    private boolean validar(String data, String origem, String destino, String peso, String vlTotal) {
        boolean valido = true;

        if (!Util.isDate(data)) {
            lblData.setForeground(Color.red);
            valido = false;
        }

        if (origem.length() < 3 || origem.length() > 30) {
            lblOrigem.setForeground(Color.red);
            valido = false;
        }

        if (destino.length() < 3 || destino.length() > 30) {
            lblDestino.setForeground(Color.red);
            valido = false;
        }
        
        if (peso.isEmpty() || !Util.isNumber(peso) || peso.length() > 10) {
            lblPeso.setForeground(Color.red);
            valido = false;
        }
        
        if (vlTotal.isEmpty() || !Util.isNumber(peso) || vlTotal.length() > 7) {
            lblValor.setForeground(Color.red);
            valido = false;
        }

        if (!valido) {
            JOptionPane.showMessageDialog(this, "Os campos com o nome em vermelho são inválidos.\nPor favor corrija.", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } 
        
        return valido;
    }
    
    private int localizarIndiceAnimal(int id) {
        int indice = 0;
        for (int i = 0; i < listaAnimal.size(); i++) {
            ModeloAnimal a = listaAnimal.get(i);
            
            if (a.getId() == id) {
                indice = i;
                break;
            } 
        }
        
        return indice;
    }
    
    private int localizarIndiceCliente(int id) {
        int indice = 0;
        for (int i = 0; i < listaCliente.size(); i++) {
            ModeloCliente c = listaCliente.get(i);
            
            if (c.getId() == id) {
                indice = i;
                break;
            } 
        }
        
        return indice;
    }
    
    private int localizarIndiceMotorista(int id) {
        int indice = 0;
        for (int i = 0; i < listaMotorista.size(); i++) {
            ModeloMotorista m = listaMotorista.get(i);
            
            if (m.getId() == id) {
                indice = i;
                break;
            } 
        }
        
        return indice;
    }
    
    private int localizarIndiceVeiculo(int id) {
        int indice = 0;
        for (int i = 0; i < listaVeiculo.size(); i++) {
            ModeloVeiculo v = listaVeiculo.get(i);
            
            if (v.getId() == id) {
                indice = i;
                break;
            } 
        }
        
        return indice;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        lblData = new javax.swing.JLabel();
        lblOrigem = new javax.swing.JLabel();
        lblDestino = new javax.swing.JLabel();
        txtDestino = new javax.swing.JTextField();
        lblPeso = new javax.swing.JLabel();
        txtPeso = new javax.swing.JTextField();
        txtData = new javax.swing.JFormattedTextField();
        lblValor = new javax.swing.JLabel();
        txtValor = new javax.swing.JFormattedTextField();
        jLabel9 = new javax.swing.JLabel();
        cmbVeiculo = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        cmbMotorista = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        cmbCliente = new javax.swing.JComboBox();
        jLabel12 = new javax.swing.JLabel();
        cmbAnimal = new javax.swing.JComboBox();
        spnQtdAnimais = new javax.swing.JSpinner(new javax.swing.SpinnerNumberModel(10, 10, 1000, 1));
        lblQtdAnimal = new javax.swing.JLabel();
        pnConsulta = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        txtConsulta = new javax.swing.JTextField();
        btnConsultar = new javax.swing.JToggleButton();
        txtOrigem = new javax.swing.JTextField();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();

        setTitle("ENTREGA GADO");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("ORDEM DE TRANSPORTE");

        lblData.setText("Data:");

        lblOrigem.setText("Origem:");

        lblDestino.setText("Destino:");

        lblPeso.setText("Peso Total:");

        try {
            txtData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (Exception ex) {      ex.printStackTrace();  }

        lblValor.setText("Valor total:");

        try {
            txtValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
        } catch (Exception ex) {      ex.printStackTrace();  }

        jLabel9.setText("Veículo:");

        jLabel10.setText("Motorista:");

        jLabel11.setText("Cliente:");

        jLabel12.setText("Animal:");

        lblQtdAnimal.setText("Quantidade total:");

        pnConsulta.setBorder(javax.swing.BorderFactory.createTitledBorder("Pesquisa"));

        jLabel13.setText("Código:");

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnConsultaLayout = new javax.swing.GroupLayout(pnConsulta);
        pnConsulta.setLayout(pnConsultaLayout);
        pnConsultaLayout.setHorizontalGroup(
            pnConsultaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnConsultaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnConsultar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnConsultaLayout.setVerticalGroup(
            pnConsultaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnConsultaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnConsultaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConsultar))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        jLabel3.setText("Código:");

        lblCodigo.setText("--");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pnConsulta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel9)
                                    .addComponent(lblValor)
                                    .addComponent(lblDestino)
                                    .addComponent(lblPeso)
                                    .addComponent(lblOrigem)
                                    .addComponent(lblData)
                                    .addComponent(jLabel12)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(cmbVeiculo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(cmbMotorista, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(cmbCliente, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(cmbAnimal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(lblQtdAnimal)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(spnQtdAnimais, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(txtOrigem, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(txtDestino, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(lblCodigo)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(txtPeso, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
                                        .addComponent(txtValor, javax.swing.GroupLayout.Alignment.LEADING)))
                                .addGap(0, 72, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(153, 153, 153)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(83, 83, 83)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(167, 167, 167)
                                .addComponent(jLabel1)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(pnConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(cmbAnimal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(spnQtdAnimais, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblQtdAnimal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(cmbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(cmbMotorista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(cmbVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblData)
                    .addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblOrigem)
                    .addComponent(txtOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDestino)
                    .addComponent(txtDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPeso)
                    .addComponent(txtPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblValor)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnSair))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExcluir)
                    .addComponent(btnAlterar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        if (txtConsulta.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Informe um valor para consulta", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            //limpa o ArrayList
            if (lista != null) {
                lista.clear();
            }
            //pesquisa apenas pelo ID
            String filtro = "id_transporte = " + txtConsulta.getText();

            try {
                lista = ctDao.consulta(filtro);

                if (lista.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "Não foram localizados ordens com o código: " + txtConsulta.getText(), "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                }

                if (lista.size() > 0) {
                    btnNovo.setText("Novo");
                    mostrarCampos(false);
                    alterarLabels();
                    if (btnExcluir.isVisible()) {
                        btnExcluir.setEnabled(true);
                        btnAlterar.setEnabled(true);
                    }
                    //como a busca é por ID só retorna 1 registro
                    ModeloConhecimentoTransporte modelo = lista.get(0);
                    String peso = Float.toString(modelo.getPeso());
                    String valor = Float.toString(modelo.getValor());
                    txtData.setText(modelo.getData());
                    txtOrigem.setText(modelo.getOrigem());
                    txtDestino.setText(modelo.getDestino());
                    txtPeso.setText(peso);
                    txtValor.setText(valor);
                    
                    //localizar os dados dos combos
                    int indiceAnimal = localizarIndiceAnimal(modelo.getAnimalId());
                    int indiceCliente = localizarIndiceCliente(modelo.getClienteId());
                    int indiceMotorista = localizarIndiceMotorista(modelo.getMotoristaId());
                    int indiceVeiculo = localizarIndiceVeiculo(modelo.getVeiculoId());
                    
                    cmbAnimal.setSelectedIndex(indiceAnimal);
                    cmbCliente.setSelectedIndex(indiceCliente);
                    cmbMotorista.setSelectedIndex(indiceMotorista);
                    cmbVeiculo.setSelectedIndex(indiceVeiculo);
                }

                
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao consultar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        if (btnNovo.getText().equals("Novo")) {
            mostrarCampos(true);
            limparCampos();
            alterarLabels();
            btnNovo.setText("Salvar");
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
                btnAlterar.setEnabled(false);
            }
        } else {
            //clicou no salvar
            if (validar(txtData.getText(), txtOrigem.getText(), txtDestino.getText(), txtPeso.getText(), txtValor.getText())) {
                ModeloAnimal a = listaAnimal.get(cmbAnimal.getSelectedIndex());
                ModeloCliente c = listaCliente.get(cmbCliente.getSelectedIndex());
                ModeloMotorista m = listaMotorista.get(cmbMotorista.getSelectedIndex());
                ModeloVeiculo v = listaVeiculo.get(cmbVeiculo.getSelectedIndex());
                
                
                ct.setAnimalId(a.getId());
                ct.setClienteId(c.getId());
                ct.setMotoristaId(m.getId());
                ct.setVeiculoId(v.getId());
                ct.setData(txtData.getText().replace("/", ""));
                ct.setQuantidadeAnimais((Integer)spnQtdAnimais.getValue());
                ct.setOrigem(txtOrigem.getText());
                ct.setDestino(txtDestino.getText());
                ct.setPeso(Float.parseFloat(txtPeso.getText()));
                ct.setValor(Float.parseFloat(txtValor.getText()));

                try {
                    if (!ctDao.incluir(ct)) {
                        JOptionPane.showMessageDialog(this, "Dados gravados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnNovo.setText("Novo");
                        int maxId = ctDao.consultaMaxId();
                        lblCodigo.setText(Integer.toString(maxId));
                        mostrarCampos(false);
                        alterarLabels();
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                            btnAlterar.setEnabled(true);
                        }
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (btnAlterar.getText().equals("Alterar")) {
            mostrarCampos(true);
            alterarLabels();
            btnAlterar.setText("Salvar");
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
            }
        } else {
            if (validar(txtData.getText(), txtOrigem.getText(), txtDestino.getText(), txtPeso.getText(), txtValor.getText())) {
                
                ModeloAnimal a = listaAnimal.get(cmbAnimal.getSelectedIndex());
                ModeloCliente c = listaCliente.get(cmbCliente.getSelectedIndex());
                ModeloMotorista m = listaMotorista.get(cmbMotorista.getSelectedIndex());
                ModeloVeiculo v = listaVeiculo.get(cmbVeiculo.getSelectedIndex());
                
                ct.setId(Integer.parseInt(lblCodigo.getText()));
                ct.setAnimalId(a.getId());
                ct.setClienteId(c.getId());
                ct.setMotoristaId(m.getId());
                ct.setVeiculoId(v.getId());
                ct.setQuantidadeAnimais((Integer)spnQtdAnimais.getValue());
                ct.setData(txtData.getText().replace("/", ""));
                ct.setOrigem(txtOrigem.getText());
                ct.setDestino(txtDestino.getText());
                ct.setPeso(Float.parseFloat(txtPeso.getText()));
                ct.setValor(Float.parseFloat(txtValor.getText()));

                try {
                    if (ctDao.alterar(ct) > 0) {
                        JOptionPane.showMessageDialog(this, "Dados alterados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnAlterar.setText("Alterar");
                        mostrarCampos(false);
                        alterarLabels();
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                        }
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        if (lblCodigo.getText().equals("--")) {
            JOptionPane.showMessageDialog(this, "Registro inválido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            lblCodigo.setForeground(Color.red);
        } else {
            try {
                int id = Integer.parseInt(lblCodigo.getText());

                if (ctDao.deletar(id) == 1) {
                    JOptionPane.showMessageDialog(this, "Registro excluido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                    limparCampos();
                    mostrarCampos(false);
                    alterarLabels();
                    btnExcluir.setEnabled(false);
                    btnAlterar.setEnabled(false);
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao excluir " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnExcluirActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JToggleButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cmbAnimal;
    private javax.swing.JComboBox cmbCliente;
    private javax.swing.JComboBox cmbMotorista;
    private javax.swing.JComboBox cmbVeiculo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblData;
    private javax.swing.JLabel lblDestino;
    private javax.swing.JLabel lblOrigem;
    private javax.swing.JLabel lblPeso;
    private javax.swing.JLabel lblQtdAnimal;
    private javax.swing.JLabel lblValor;
    private javax.swing.JPanel pnConsulta;
    private javax.swing.JSpinner spnQtdAnimais;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JFormattedTextField txtData;
    private javax.swing.JTextField txtDestino;
    private javax.swing.JTextField txtOrigem;
    private javax.swing.JTextField txtPeso;
    private javax.swing.JFormattedTextField txtValor;
    // End of variables declaration//GEN-END:variables

}
